// 生成目录
const fs = require('fs')
const path = require('path')

const excludeEntry = [
  '.git',
  '.idea',
  '.gitignore',
  'createDir.js',
  'generateCatalog.js',
  'LICENSE',
  'readme.md',
  '.editorconfig'
].map(item => path.resolve(__dirname, item))

// 去掉s变量之后的所有内容，重新生成目录
const s = `## -----------------华丽的分割线-------------------`
const splitReg = new RegExp(`${s}[\\S\\W]*`, 'g')
let rawContent = fs.readFileSync('./readme.md').toString()
rawContent = `${rawContent.replace(splitReg, '')}${s}\n\n`

const isDir = path => {
  return fs.statSync(path).isDirectory()
}

const prefix = l => {
  // markdown目录结构需要偶数个的空格才行
  return (l === 1) ? '## ' : ((l % 2 !== 0) ? ' '.repeat(l + 1) : ' '.repeat(l)) + '- '
}

// gitee需要将`\`换成`/`，否则会404
const pathSep = path => path.replace(/\\/g, '/')
  

// 递归遍历所有的目录文件
const readDeepDir = (root = __dirname, parentPath = './') => {
  const rootPath = path.resolve(root, parentPath)
  const dirs = fs.readdirSync(rootPath)
  dirs.forEach(dir => {
    const dirPath = path.resolve(rootPath, dir)
    const catalog = pathSep(dirPath.split(`front-end-question${path.sep}`)[1])
    const length = catalog.split('/').length   // 可以从这里判断是几级目录
    // 不遍历存在excludeEntry的目录和只遍历最多三级目录
    if (excludeEntry.includes(dirPath) || length > 3) return
    // 递归，并将改文件夹写入目录中
    if (isDir(dirPath)) {
      rawContent += `${prefix(length)}[${pathSep(dir)}](./${(catalog)})\n`
      readDeepDir(rootPath, dirPath)
    } else {
      rawContent += `${prefix(length)}[${catalog}](./${catalog})\n`
    }
  })
}

readDeepDir()
fs.writeFileSync('./readme.md', rawContent)
console.log('目录生成成功！！')
